<?php

CCore::Using('base.datetime');

abstract class CBaseInputData
{
	/**
	 * @param string $mValue
	 * @return string
	 */
	protected function cleanValue($mValue)
	{
		return $mValue;
	}
}

class CInputData extends CBaseInputData
{
	/**
	 * @var bool
	 */
	private $_bMagicQuotesOn;

	/**
	 * @return CPostInputData
	 */
	public function __construct()
	{
		$this->_bMagicQuotesOn = (bool) @get_magic_quotes_gpc();
	}

	/**
	 * @param string $sKey
	 * @param mixed $nmDefault = null
	 * @return mixed
	 */
	public function GetCookieValue($sKey, $nmDefault = null)
	{
		return (isset($_COOKIE[$sKey])) ? $this->cleanValue($_COOKIE[$sKey]) : $nmDefault;
	}

	/**
	 * @param string $sKey
	 * @param mixed $nmDefault = null
	 * @return mixed
	 */
	public function GetHeaderValue($sKey, $nmDefault = null)
	{
		$sHeaderKey = 'HTTP_'.str_replace('-', '_', strtoupper($sKey));
		return (isset($_SERVER[$sHeaderKey])) ? $_SERVER[$sHeaderKey] : $nmDefault;
	}

	/**
	 * @param string $sKey
	 * @param mixed $nmDefault = null
	 * @return mixed
	 */
	public function GetPostValue($sKey, $nmDefault = null)
	{
		return (isset($_POST[$sKey])) ? $this->cleanValue($_POST[$sKey]) : $nmDefault;
	}

	/**
	 * @param string $sKey
	 * @param mixed $nmDefault = null
	 * @return mixed
	 */
	public function GetQueryValue($sKey, $nmDefault = null)
	{
		return (isset($_GET[$sKey])) ? $this->cleanValue($_GET[$sKey]) : $nmDefault;
	}

	/**
	 * @return string
	 */
	public function ServerProtocol()
	{
		return (isset($_SERVER['SERVER_PROTOCOL']) && !empty($_SERVER['SERVER_PROTOCOL']))
			? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0';
	}
	
	/**
	 * @return void
	 */
	public function ServerNotModifiedCache($iExpireTime)
	{
		if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && !empty($_SERVER['HTTP_IF_MODIFIED_SINCE']))
		{
			header($this->ServerProtocol().' 304 Not Modified');
			header('Cache-Control: Public');
			header('Pragma: Public');
			header('Last-Modified: '.$_SERVER['HTTP_IF_MODIFIED_SINCE']);
			header('Expires: '.date('D, j M Y H:i:s', CCoreBaseDateTime::GetUtcTimeStamp() + $iExpireTime).' UTC');
			header('Content-Length: 0');
			return true;
		}
		else
		{
			header('Cache-Control: Public');
			header('Pragma: Public');
			header('Last-Modified: '.gmdate('D, d M Y H:i:s', CCoreBaseDateTime::GetUtcTimeStamp() - $iExpireTime).' UTC');
			header('Expires: '.date('D, j M Y H:i:s', CCoreBaseDateTime::GetUtcTimeStamp() + $iExpireTime).' UTC');
		}
		return false;
	}

	/**
	 * @param string $mValue
	 * @return string
	 */
	protected function cleanValue($mValue)
	{
		if (!$this->_bMagicQuotesOn)
		{
			return $mValue;
		}

		$mResult = null;
        if (is_array($mValue))
        {
			if (0 < count($mValue))
			{
				$mResult = array();
				foreach ($mValue as $sArrayKey => $mArrayValue)
				{
					$mResult[$sArrayKey] = $this->cleanValue($mArrayValue);
				}
			}
        }
        else
        {
            $mResult = stripslashes($mValue);
        }
		
        return $mResult;
	}
}